<template>
  <div v-loading="loading" class="bg-#F8F9FB" style="min-height: calc(100vh - 50px); padding: 20px">
    <div class="text-20px font-bold p-20px flex justify-between items-center">
      <span>版本管理</span>
      <div>
        <el-button type="primary" @click="onGetPrivacySetting">隐私协议</el-button>
        <el-button type="success">
          <el-icon class="mr-1"><Link /></el-icon>
          配置域名
        </el-button>
        <el-button type="primary" :loading="loading" @click="loadVersionInfo">
          <el-icon class="mr-1"><Refresh /></el-icon>
          {{ loading ? '刷新中...' : '刷新版本信息' }}
        </el-button>
      </div>
    </div>

    <!-- 正式版本 -->
    <div class="app-content">
      <h3 class="font-normal text-20px mb-5 flex items-end">
        <span class="mr-2.5">正式版本</span>
      </h3>
      <div v-if="currentVersion" class="flex justify-between items-center mt-5">
        <div>
          <p class="text-gray-500 mb-2.5">版本号</p>
          <p>{{ currentVersion.version }}</p>
        </div>
        <div>
          <p><span>发布时间：</span>{{ currentVersion.releaseTime }}</p>
          <p class="mt-2.5"><span>项目备注：</span>{{ currentVersion.remark }}</p>
          <p class="mt-2.5">
            <span class="text-gray-500">服务状态：</span>
            <el-tag :type="serviceStatusInfo.type" size="small">
              {{ serviceStatusInfo.text }}
            </el-tag>
          </p>
        </div>
        <div>
          <el-button type="warning" class="w-120px" @click="onRevertVersion">
            <el-icon class="mr-1"><Back /></el-icon>
            版本回退
          </el-button>
          <el-button v-if="serviceStatus === 1" type="primary" class="w-120px ml-2" @click="onServiceAction('close')">
            <el-icon class="mr-1"><VideoPause /></el-icon>
            暂停服务
          </el-button>
          <el-button v-else-if="serviceStatus === 0" type="primary" class="w-120px ml-2" @click="onServiceAction('open')">
            <el-icon class="mr-1"><VideoPlay /></el-icon>
            恢复服务
          </el-button>
          <el-button v-else type="info" class="w-120px ml-2" disabled>
            <el-icon class="mr-1"><Loading /></el-icon>
            获取状态中
          </el-button>
        </div>
      </div>
      <div v-else class="flex items-center justify-center h-25 text-gray-500">暂无正式版本</div>
    </div>

    <!-- 审核版本 -->
    <div class="app-content">
      <h3 class="font-normal text-20px mb-5 flex items-end">
        <span class="mr-2.5">审核版本</span>
      </h3>
      <div v-if="auditVersion" class="flex justify-between items-center">
        <div>
          <p class="text-gray-500 mb-2.5">版本号</p>
          <p>{{ auditVersion.version }}</p>
          <p class="mt-2.5">
            <el-tag :type="auditVersion.statusType" size="small">
              {{ auditVersion.statusText }}
            </el-tag>
          </p>
        </div>
        <div>
          <p><span>提交时间：</span>{{ auditVersion.submitTime }}</p>
          <p class="mt-2.5"><span>项目备注：</span>{{ auditVersion.remark }}</p>
          <p v-if="auditVersion.auditid" class="mt-2.5"><span class="text-gray-500">审核ID：</span>{{ auditVersion.auditid }}</p>
          <div v-if="auditVersion.status === 1 && auditVersion.reason" class="mt-2.5">
            <p class="text-red-500"><span>拒绝原因：</span>{{ auditVersion.reason }}</p>
          </div>
        </div>
        <div>
          <el-button v-if="auditVersion.status === 2" type="warning" @click="onUndoAudit">
            <el-icon class="mr-1"><Close /></el-icon>
            撤回审核
          </el-button>
          <el-button v-if="auditVersion.status === 1" type="danger" @click="showRejectReason">
            <el-icon class="mr-1"><Warning /></el-icon>
            查看详情
          </el-button>
          <el-button v-if="auditVersion.status === 0" type="success" @click="onReleaseVersion">
            <el-icon class="mr-1"><Promotion /></el-icon>
            发布版本
          </el-button>
        </div>
      </div>
      <div v-else class="flex items-center justify-center h-25 text-gray-500">暂无审核版本</div>
    </div>

    <!-- 体验版本 -->
    <div class="app-content">
      <h3 class="font-normal text-20px mb-5 flex items-end">
        <span class="mr-2.5">体验版本</span>
      </h3>
      <div v-if="latestVersion" class="flex justify-between items-center">
        <div>
          <p class="text-gray-500 mb-2.5">版本号</p>
          <p>{{ latestVersion.version }}</p>
        </div>
        <div>
          <p><span>提交时间：</span>{{ latestVersion.submitTime }}</p>
          <p class="mt-2.5"><span>项目备注：</span>{{ latestVersion.remark }}</p>
        </div>
        <div>
          <el-button type="success" @click="onGetTrialQRCode()">
            <el-icon class="mr-1"><FullScreen /></el-icon>
            获取体验二维码
          </el-button>
          <el-button type="primary" :disabled="!!auditVersion && auditVersion.status === 2" @click="onSubmitAudit()">
            <el-icon class="mr-1"><Upload /></el-icon>
            提交审核
          </el-button>
        </div>
      </div>
      <div v-else class="flex items-center justify-center h-25 text-gray-500">暂无体验版本</div>
    </div>

    <!-- 代码提交 -->
    <div class="app-content">
      <h3 class="font-normal text-20px mb-5 flex items-end">
        <span class="mr-2.5">代码提交</span>
      </h3>

      <div v-if="updateVersion" class="flex justify-between items-center">
        <div>
          <p><span class="text-gray-500">当前版本：</span>{{ updateVersion.version || '无' }}</p>
          <p class="mt-2.5"><span class="text-gray-500">新版本：</span>{{ updateVersion.newVersion }}</p>
        </div>
        <div>
          <p v-if="updateVersion.update">有新版本可以上传</p>
          <p v-else>当前版本已经提交到测试</p>
          <p class="mt-2.5">
            <span class="text-gray-500">更新说明：{{ updateVersion.desc }}</span>
          </p>
        </div>
        <div>
          <el-button v-if="updateVersion.update" type="success" @click="CommentCode()">
            <el-icon class="mr-1"><DocumentAdd /></el-icon>
            提交代码
          </el-button>
          <el-button v-else @click="CommentCode()">
            <el-icon class="mr-1"><Refresh /></el-icon>
            重新提交
          </el-button>
          <!-- 
          <el-button @click="onSubmitAudit()">测试审核</el-button>
          <el-button @click="onGetAuditStatus()">测试审核</el-button> -->
        </div>
      </div>
      <div v-else class="flex items-center justify-center h-25 text-gray-500">暂无新版本</div>
    </div>

    <!-- 提交代码弹窗 -->
    <el-dialog
      v-model="commentDialogVisible"
      title="提交代码"
      width="500px"
      :before-close="() => (commentDialogVisible = false)"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div v-loading="commentLoading" loading-text="正在提交代码，请稍候...">
        <el-form :model="commentForm" label-width="80px">
          <el-form-item label="版本号" required>
            <el-input v-model="commentForm.version" placeholder="请输入版本号，如：1.1.1" :disabled="commentLoading" />
          </el-form-item>
          <el-form-item label="更新内容" required>
            <el-input
              v-model="commentForm.desc"
              type="textarea"
              :rows="4"
              placeholder="请输入本次更新的内容说明"
              :disabled="commentLoading"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button :disabled="commentLoading" @click="commentDialogVisible = false">
            <el-icon class="mr-1"><Close /></el-icon>
            取消
          </el-button>
          <el-button type="primary" :loading="commentLoading" :disabled="commentLoading" @click="onConfirmCommit">
            <el-icon class="mr-1"><DocumentAdd /></el-icon>
            {{ commentLoading ? '提交中...' : '确定提交' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 路径选择弹窗 -->
    <el-dialog
      v-model="pathDialogVisible"
      title="选择页面路径"
      width="500px"
      :before-close="() => (pathDialogVisible = false)"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div v-loading="pathLoading" :loading-text="dialogQrcode ? '正在生成二维码...' : '正在获取页面路径...'">
        <el-form label-width="100px" label-position="left">
          <el-form-item label="页面路径" required>
            <el-select
              v-model="selectedPath"
              placeholder="请选择页面路径"
              filterable
              :disabled="pathLoading"
              style="width: 100%"
              clearable
              @change="onPathChange"
            >
              <el-option v-for="option in pathOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-alert
              title="提示"
              type="info"
              description="选择一个页面路径来生成对应页面的体验二维码，用户扫码后将直接进入该页面。"
              show-icon
              :closable="false"
            />
          </el-form-item>

          <!-- 二维码显示区域 -->
          <el-form-item v-if="dialogQrcode" label="体验二维码">
            <div class="text-center">
              <img :src="dialogQrcode" alt="体验二维码" style="width: 200px; height: 200px; border: 1px solid #ddd; border-radius: 8px" />
              <div class="mt-3">
                <el-button type="primary" @click="onSaveQRCode">
                  <el-icon class="mr-1"><Download /></el-icon>
                  保存二维码
                </el-button>
                <el-button @click="dialogQrcode = ''">
                  <el-icon class="mr-1"><Refresh /></el-icon>
                  重新生成
                </el-button>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button :disabled="pathLoading" @click="pathDialogVisible = false">
            <el-icon class="mr-1"><Close /></el-icon>
            {{ dialogQrcode ? '关闭' : '取消' }}
          </el-button>
          <el-button
            v-if="!dialogQrcode"
            type="primary"
            :loading="pathLoading"
            :disabled="pathLoading || !selectedPath"
            @click="onConfirmGetQRCode"
          >
            <el-icon class="mr-1"><QrCode /></el-icon>
            {{ pathLoading ? '获取中...' : '获取二维码' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 版本回退弹窗 -->
    <el-dialog
      v-model="revertDialogVisible"
      title="版本回退"
      width="600px"
      :before-close="() => (revertDialogVisible = false)"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div v-loading="revertLoading" :loading-text="showHistoryVersions ? '正在执行回退...' : '正在获取历史版本...'">
        <el-alert
          title="注意"
          type="warning"
          description="版本回退后，用户将使用回退后的版本。请谨慎操作！"
          show-icon
          :closable="false"
          class="mb-4"
        />

        <el-form label-width="100px" label-position="left">
          <el-form-item label="回退选项">
            <el-radio-group v-model="selectedVersion" :disabled="revertLoading">
              <el-radio value="">回退到上一个版本</el-radio>
              <el-radio value="specific">选择指定版本</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="selectedVersion === 'specific'" label="历史版本">
            <div v-if="!showHistoryVersions" class="mb-3">
              <el-button type="primary" :loading="revertLoading" size="small" @click="loadHistoryVersions">
                {{ revertLoading ? '加载中...' : '加载历史版本' }}
              </el-button>
            </div>

            <div v-else>
              <div v-if="historyVersions.length === 0" class="text-gray-500 text-center">
                <p>暂无历史版本数据</p>
                <p class="text-sm">无法选择指定版本进行回退</p>
              </div>
              <el-select
                v-else
                v-model="selectedVersionOption"
                placeholder="请选择要回退的版本"
                style="width: 100%; min-width: 200px"
                :disabled="revertLoading"
              >
                <el-option
                  v-for="version in historyVersions"
                  :key="version.app_version"
                  :label="`${version.user_version} (${version.commitTimeFormatted})`"
                  :value="version.app_version.toString()"
                >
                  <div>
                    <div>版本：{{ version.user_version }}</div>
                    <div class="text-gray-500 text-sm">描述：{{ version.user_desc }} | 时间：{{ version.commitTimeFormatted }}</div>
                  </div>
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button :disabled="revertLoading" @click="revertDialogVisible = false"> 取消 </el-button>
          <el-button type="warning" :loading="revertLoading" :disabled="isRevertButtonDisabled" @click="onConfirmRevert">
            {{ revertLoading ? '回退中...' : '确定回退' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提交审核弹窗 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="提交审核"
      width="500px"
      :before-close="() => (auditDialogVisible = false)"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div v-loading="auditLoading" loading-text="正在提交审核，请稍候...">
        <el-alert
          title="提示"
          type="info"
          description="提交审核后，微信官方将对您的小程序进行审核，审核通过后即可发布上线。"
          show-icon
          :closable="false"
        />

        <el-form :model="auditForm" label-width="100px" label-position="left" class="mt-4">
          <el-form-item label="版本描述" required>
            <el-input
              v-model="auditForm.version_desc"
              type="textarea"
              :rows="4"
              placeholder="请输入本次提交审核的版本描述，如：新增功能、修复问题等"
              :disabled="auditLoading"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button :disabled="auditLoading" @click="auditDialogVisible = false">
            <el-icon class="mr-1"><Close /></el-icon>
            取消
          </el-button>
          <el-button type="primary" :loading="auditLoading" :disabled="auditLoading" @click="onConfirmSubmitAudit">
            {{ auditLoading ? '提交中...' : '确定提交' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 隐私协议弹窗 -->
    <el-dialog
      v-model="privacyDialogVisible"
      :title="isEditingPrivacy ? '更新隐私协议' : '隐私协议设置'"
      width="800px"
      :before-close="() => (privacyDialogVisible = false)"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <!-- 版本切换 -->
      <div v-if="!isEditingPrivacy" class="mb-4">
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <span class="text-sm text-gray-600 mr-3">查看版本：</span>
            <el-radio-group v-model="privacyVersion" size="small" @change="onPrivacyVersionChange">
              <el-radio :value="1">线上版本</el-radio>
              <el-radio :value="2">开发版本</el-radio>
            </el-radio-group>
          </div>
          <div v-if="privacyVersion === 2" class="text-xs text-orange-500">
            <el-icon class="mr-1"><Warning /></el-icon>
            开发版本修改后需重新提交审核才能生效
          </div>
        </div>
      </div>

      <!-- 显示当前配置 -->
      <div v-if="!isEditingPrivacy && privacyData">
        <div class="mb-6">
          <h4 class="text-base font-medium mb-4">当前隐私设置</h4>
          <div v-if="privacyData.setting_list && privacyData.setting_list.length > 0" class="mb-6">
            <el-table :data="enhancedSettingList" :border="true" class="privacy-table">
              <el-table-column label="隐私类型" prop="privacy_key" width="120" align="center" />
              <el-table-column label="中文描述" prop="privacy_desc" width="200" />
              <el-table-column label="收集用途" prop="privacy_text" show-overflow-tooltip />
            </el-table>
          </div>
          <div v-else class="text-gray-500 text-center py-4">暂无隐私设置配置</div>

          <div class="mt-6">
            <h4 class="text-base font-medium mb-4">联系方式</h4>
            <div class="grid grid-cols-2 gap-4">
              <div>联系电话：{{ privacyData.owner_setting?.contact_phone || '未设置' }}</div>
              <div>联系邮箱：{{ privacyData.owner_setting?.contact_email || '未设置' }}</div>
              <div>联系QQ：{{ privacyData.owner_setting?.contact_qq || '未设置' }}</div>
              <div>联系微信：{{ privacyData.owner_setting?.contact_weixin || '未设置' }}</div>
            </div>
            <div class="mt-4">
              <div>通知方式：{{ privacyData.owner_setting?.notice_method || '未设置' }}</div>
            </div>
          </div>
        </div>

        <div class="text-center">
          <el-button type="primary" @click="onStartEditPrivacy">
            <el-icon class="mr-1"><Edit /></el-icon>
            更新隐私协议
          </el-button>
        </div>
      </div>

      <!-- 编辑隐私协议 -->
      <div v-else-if="isEditingPrivacy">
        <privacy-setting-form
          :initial-data="privacyData"
          :template-data="templateData"
          :privacy-version="privacyVersion"
          @submit="onSubmitPrivacyUpdate"
          @cancel="onCancelEditPrivacy"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="privacyDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, inject, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  commit,
  getAuditStatus,
  getCodePage,
  getTrialQRCode,
  submitAudit,
  getVersionInfo,
  getLatestAuditStatus,
  release,
  revertCodeRelease,
  setVisitStatus,
  getVisitStatus,
  getPrivacySetting,
  setPrivacySetting,
  undoAudit,
  getOpenTemplate
} from '@/api/platform/app/wechat_open.js'
import PrivacySettingForm from './PrivacySettingForm.vue'

defineOptions({
  name: 'DkWechatUploadOpen'
})

const privacySettings = ref([])

const defaultApp = inject('defaultApp')
const loading = ref(false)

const qrcode = ref('')

// 版本信息数据
const currentVersion = ref(null)
const auditVersion = ref(null)
const latestVersion = ref(null)
const serviceStatus = ref(null) // 服务状态：null-未知，0-已暂停，1-正常

const updateVersion = ref({
  version: '1.1.0',
  newVersion: '1.1.1',
  update: true,
  desc: '修复了一些已知问题，优化用户体验'
})

// 提交代码弹窗相关
const commentDialogVisible = ref(false)
const commentLoading = ref(false)
const commentForm = ref({
  version: '',
  desc: ''
})

// 路径选择弹窗相关
const pathDialogVisible = ref(false)
const pathLoading = ref(false)
const selectedPath = ref('')
const pathOptions = ref([])
const dialogQrcode = ref('')

// 版本回退弹窗相关
const revertDialogVisible = ref(false)
const revertLoading = ref(false)
const historyVersions = ref([])
const selectedVersion = ref('')
const selectedVersionOption = ref('') // 用于选择具体版本
const showHistoryVersions = ref(false)

// 提交审核弹窗相关
const auditDialogVisible = ref(false)
const auditLoading = ref(false)
const auditForm = ref({
  version_desc: ''
})

// 计算属性：确定回退按钮是否禁用
const isRevertButtonDisabled = computed(() => {
  if (revertLoading.value) return true

  // 如果选择了指定版本模式
  if (selectedVersion.value === 'specific') {
    // 没有加载历史版本或没有历史版本数据或没有选择具体版本
    return !showHistoryVersions.value || historyVersions.value.length === 0 || !selectedVersionOption.value
  }

  // 回退到上一个版本模式，不需要额外条件
  return false
})

// 计算属性：服务状态显示文本和样式
const serviceStatusInfo = computed(() => {
  if (serviceStatus.value === null) {
    return { text: '获取中...', type: 'info', color: '#909399' }
  } else if (serviceStatus.value === 1) {
    return { text: '服务正常', type: 'success', color: '#67C23A' }
  } else if (serviceStatus.value === 0) {
    return { text: '服务已暂停', type: 'danger', color: '#F56C6C' }
  } else {
    return { text: '状态未知', type: 'warning', color: '#E6A23C' }
  }
})

// 计算属性：增强的隐私设置列表（包含中文描述）
const enhancedSettingList = computed(() => {
  if (!privacyData.value?.setting_list || !privacyData.value?.privacy_desc?.privacy_desc_list) {
    return []
  }

  // 创建中文描述映射表
  const descMap = {}
  privacyData.value.privacy_desc.privacy_desc_list.forEach((item) => {
    descMap[item.privacy_key] = item.privacy_desc
  })

  // 增强设置列表，添加中文描述
  return privacyData.value.setting_list.map((setting) => ({
    ...setting,
    privacy_desc: descMap[setting.privacy_key] || (setting.privacy_key === '自定义' ? '自定义类型' : '未知类型')
  }))
})

const CommentCode = () => {
  // 先获取模板数据，然后打开弹窗
  const loadingMessage = ElMessage({
    type: 'info',
    message: '正在获取模板信息...',
    duration: 0
  })

  getOpenTemplate(defaultApp.value.id)
    .then((res) => {
      loadingMessage.close()
      console.log('模板信息:', res)

      if (res.data) {
        // 使用模板数据填充表单
        commentForm.value = {
          version: res.data.version || '',
          desc: res.data.desc || ''
        }
        commentDialogVisible.value = true
      } else {
        ElMessage.error('获取模板信息失败')
      }
    })
    .catch((err) => {
      loadingMessage.close()
      console.error('获取模板信息失败:', err)
      ElMessage.error('获取模板信息失败')
    })
}

// 确认提交代码
const onConfirmCommit = () => {
  if (!commentForm.value.version || !commentForm.value.desc) {
    ElMessage.warning('请填写版本号和更新内容')
    return
  }

  // 开始加载
  commentLoading.value = true

  console.log('提交代码参数:', {
    id: defaultApp.value.id,
    version: commentForm.value.version,
    desc: commentForm.value.desc
  })

  commit(defaultApp.value.id, commentForm.value.version, commentForm.value.desc)
    .then((res) => {
      console.log(res)
      ElMessage.success('代码提交成功')
      commentDialogVisible.value = false
      // 更新版本信息
      updateVersion.value.version = commentForm.value.version
      updateVersion.value.desc = commentForm.value.desc
      // 刷新版本信息
      setTimeout(() => {
        loadVersionInfo()
      }, 1000)
    })
    .catch((err) => {
      console.error('提交失败:', err)
      ElMessage.error('代码提交失败' + err.msg)
    })
    .finally(() => {
      // 结束加载
      commentLoading.value = false
    })
}

const onGetCodePage = () => {
  getCodePage(defaultApp.value.id).then((res) => {
    console.log(res)
  })
}

const onGetTrialQRCode = () => {
  // 打开路径选择弹窗
  selectedPath.value = ''
  dialogQrcode.value = ''
  pathDialogVisible.value = true
  // 获取页面路径列表
  loadPagePaths()
}

// 加载页面路径列表
const loadPagePaths = () => {
  pathLoading.value = true
  getCodePage(defaultApp.value.id)
    .then((res) => {
      console.log('页面路径列表:', res)
      // 将数组转换为 el-select 需要的格式
      pathOptions.value = res.data.map((path, index) => ({
        label: path,
        value: path
      }))
    })
    .catch((err) => {
      console.error('获取页面路径失败:', err)
      ElMessage.error('获取页面路径失败')
    })
    .finally(() => {
      pathLoading.value = false
    })
}

// 确认获取体验二维码
const onConfirmGetQRCode = () => {
  if (!selectedPath.value) {
    ElMessage.warning('请选择页面路径')
    return
  }

  pathLoading.value = true
  getTrialQRCode(defaultApp.value.id, selectedPath.value)
    .then((res) => {
      console.log('体验二维码:', res)
      dialogQrcode.value = res.data
      qrcode.value = res.data
      ElMessage.success('体验二维码获取成功')
    })
    .catch((err) => {
      console.error('获取体验二维码失败:', err)
      ElMessage.error('获取体验二维码失败')
    })
    .finally(() => {
      pathLoading.value = false
    })
}

// 路径变化时清空二维码
const onPathChange = () => {
  if (dialogQrcode.value) {
    dialogQrcode.value = ''
  }
}

// 保存二维码
const onSaveQRCode = () => {
  if (!dialogQrcode.value) {
    ElMessage.warning('请先生成二维码')
    return
  }

  // 创建一个临时的a标签来下载图片
  const link = document.createElement('a')
  link.href = dialogQrcode.value
  link.download = `体验二维码_${selectedPath.value.replace(/\//g, '_')}_${Date.now()}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('二维码保存成功')
}

// 显示审核拒绝详情
const showRejectReason = () => {
  if (!auditVersion.value || !auditVersion.value.reason) {
    ElMessage.warning('暂无拒绝详情')
    return
  }

  ElMessage({
    type: 'error',
    message: `审核被拒绝：${auditVersion.value.reason}`,
    duration: 0,
    showClose: true
  })
}

// 发布版本
const onReleaseVersion = () => {
  if (!auditVersion.value || auditVersion.value.status !== 0) {
    ElMessage.warning('只有审核通过的版本才能发布')
    return
  }

  ElMessageBox.confirm(`确定要发布版本 ${auditVersion.value.version} 上线吗？发布后用户将可以在微信中搜索到您的小程序。`, '发布版本确认', {
    confirmButtonText: '确定发布',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: false
  })
    .then(() => {
      // 用户确认发布
      performRelease()
    })
    .catch(() => {
      // 用户取消发布
      ElMessage.info('已取消发布')
    })
}

// 执行发布操作
const performRelease = () => {
  const loadingMessage = ElMessage({
    type: 'info',
    message: '正在发布版本，请稍候...',
    duration: 0
  })

  release(defaultApp.value.id)
    .then((res) => {
      console.log('发布结果:', res)
      loadingMessage.close()

      if (res.data && res.data.errcode === 0) {
        ElMessage.success('版本发布成功！用户现在可以搜索到您的小程序了')
        // 刷新版本信息
        setTimeout(() => {
          loadVersionInfo()
        }, 1000)
      } else {
        const errorMsg = res.data?.errmsg || '发布失败'
        ElMessage.error(`发布失败: ${errorMsg}`)
      }
    })
    .catch((err) => {
      console.error('发布异常:', err)
      loadingMessage.close()
    })
}

// 版本回退
const onRevertVersion = () => {
  if (!currentVersion.value) {
    ElMessage.warning('暂无正式版本可回退')
    return
  }

  // 重置状态
  selectedVersion.value = ''
  selectedVersionOption.value = ''
  historyVersions.value = []
  showHistoryVersions.value = false
  revertDialogVisible.value = true
}

// 获取历史版本列表
const loadHistoryVersions = () => {
  revertLoading.value = true
  revertCodeRelease(defaultApp.value.id, '', 1)
    .then((res) => {
      console.log('历史版本列表:', res)
      if (res.data && res.data.errcode === 0 && res.data.version_list) {
        if (res.data.version_list.length > 0) {
          historyVersions.value = res.data.version_list.map((version) => ({
            ...version,
            commitTimeFormatted: new Date(version.commit_time * 1000).toLocaleString('zh-CN')
          }))
          showHistoryVersions.value = true
          ElMessage.success('历史版本加载成功')
        } else {
          historyVersions.value = []
          showHistoryVersions.value = true
          ElMessage.warning('暂无历史版本数据')
        }
      } else {
        ElMessage.warning('暂无历史版本数据')
      }
    })
    .catch((err) => {
      console.error('获取历史版本失败:', err)
      ElMessage.error('获取历史版本失败')
    })
    .finally(() => {
      revertLoading.value = false
    })
}

// 确认回退版本
const onConfirmRevert = () => {
  const isSpecificVersion = selectedVersion.value === 'specific'
  const versionToUse = isSpecificVersion ? selectedVersionOption.value : ''
  const confirmMessage = isSpecificVersion ? `确定要回退到指定版本吗？\n版本：${selectedVersionOption.value}` : '确定要回退到上一个版本吗？'

  ElMessageBox.confirm(confirmMessage, '版本回退确认', {
    confirmButtonText: '确定回退',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      performRevert(versionToUse)
    })
    .catch(() => {
      ElMessage.info('已取消回退')
    })
}

// 执行回退操作
const performRevert = (versionToRevert = '') => {
  revertLoading.value = true

  const loadingMessage = ElMessage({
    type: 'info',
    message: '正在执行版本回退，请稍候...',
    duration: 0
  })

  revertCodeRelease(defaultApp.value.id, versionToRevert, 0)
    .then((res) => {
      console.log('回退结果:', res)
      loadingMessage.close()

      if (res.data && res.data.errcode === 0) {
        ElMessage.success('版本回退成功！')
        revertDialogVisible.value = false
        // 刷新版本信息
        setTimeout(() => {
          loadVersionInfo()
        }, 1000)
      } else {
        const errorMsg = res.data?.errmsg || '回退失败'
        ElMessage.error(`版本回退失败: ${errorMsg}`)
      }
    })
    .catch((err) => {
      console.error('回退异常:', err)
      loadingMessage.close()
    })
    .finally(() => {
      revertLoading.value = false
    })
}

// 服务操作
const onServiceAction = (action) => {
  const actionText = action === 'close' ? '暂停' : '恢复'
  const statusText = action === 'close' ? '暂停服务后，用户将无法访问您的小程序' : '恢复服务后，用户可以正常访问您的小程序'

  ElMessageBox.confirm(`确定要${actionText}小程序服务吗？\n${statusText}`, `${actionText}服务确认`, {
    confirmButtonText: `确定${actionText}`,
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      performServiceAction(action)
    })
    .catch(() => {
      ElMessage.info(`已取消${actionText}服务`)
    })
}

// 执行服务操作
const performServiceAction = (action) => {
  const actionText = action === 'close' ? '暂停' : '恢复'

  const loadingMessage = ElMessage({
    type: 'info',
    message: `正在${actionText}服务，请稍候...`,
    duration: 0
  })

  setVisitStatus(defaultApp.value.id, action)
    .then((res) => {
      console.log('服务状态切换结果:', res)
      loadingMessage.close()

      if (res.data && res.data.errcode === 0) {
        ElMessage.success(`小程序服务${actionText}成功！`)
        // 更新服务状态
        serviceStatus.value = action === 'close' ? 0 : 1
      } else {
        const errorMsg = res.data?.errmsg || `${actionText}失败`
        ElMessage.error(`服务${actionText}失败: ${errorMsg}`)
      }
    })
    .catch((err) => {
      console.error('服务状态切换异常:', err)
      loadingMessage.close()
    })
}

// 获取服务状态
const loadServiceStatus = () => {
  getVisitStatus(defaultApp.value.id)
    .then((res) => {
      console.log('服务状态查询结果:', res)
      if (res.data && res.data.errcode === 0) {
        serviceStatus.value = res.data.status
      } else {
        console.error('获取服务状态失败:', res.data?.errmsg || '未知错误')
        serviceStatus.value = null
      }
    })
    .catch((err) => {
      console.error('获取服务状态异常:', err)
      serviceStatus.value = null
    })
}

// 隐私协议弹窗相关
const privacyDialogVisible = ref(false)
const privacyData = ref(null)
const isEditingPrivacy = ref(false)
const templateData = ref(null) // 存储模板数据
const privacyVersion = ref(1) // 隐私协议版本：1-线上版本，2-开发版本

// 获取隐私设置
const onGetPrivacySetting = () => {
  const loadingMessage = ElMessage({
    type: 'info',
    message: '正在获取隐私设置，请稍候...',
    duration: 0
  })

  // 同时获取隐私设置和模板数据
  Promise.all([getPrivacySetting(defaultApp.value.id, privacyVersion.value), getOpenTemplate(defaultApp.value.id)])
    .then(([privacyRes, templateRes]) => {
      console.log('隐私设置查询结果:', privacyRes)
      console.log('模板数据查询结果:', templateRes)
      loadingMessage.close()

      if (privacyRes.data && privacyRes.data.errcode === 0) {
        privacyData.value = privacyRes.data

        // 存储模板数据
        if (templateRes.data) {
          templateData.value = templateRes.data
        }

        isEditingPrivacy.value = false
        privacyDialogVisible.value = true
      } else {
        const errorMsg = privacyRes.data?.errmsg || '获取隐私设置失败'
        ElMessage.error(`获取隐私设置失败: ${errorMsg}`)
      }
    })
    .catch((err) => {
      console.error('获取隐私设置异常:', err)
      loadingMessage.close()
      ElMessage.error('获取隐私设置异常')
    })
}

// 切换隐私协议版本
const onPrivacyVersionChange = () => {
  const loadingMessage = ElMessage({
    type: 'info',
    message: '正在切换版本，请稍候...',
    duration: 0
  })

  // 重新获取对应版本的隐私设置
  Promise.all([getPrivacySetting(defaultApp.value.id, privacyVersion.value), getOpenTemplate(defaultApp.value.id)])
    .then(([privacyRes, templateRes]) => {
      console.log('切换版本后的隐私设置:', privacyRes)
      loadingMessage.close()

      if (privacyRes.data && privacyRes.data.errcode === 0) {
        privacyData.value = privacyRes.data

        // 更新模板数据
        if (templateRes.data) {
          templateData.value = templateRes.data
        }

        ElMessage.success(`已切换到${privacyVersion.value === 1 ? '线上' : '开发'}版本`)
      } else {
        const errorMsg = privacyRes.data?.errmsg || '获取隐私设置失败'
        ElMessage.error(`获取隐私设置失败: ${errorMsg}`)
      }
    })
    .catch((err) => {
      console.error('切换版本异常:', err)
      loadingMessage.close()
      ElMessage.error('切换版本异常')
    })
}

// 开始编辑隐私协议
const onStartEditPrivacy = () => {
  isEditingPrivacy.value = true
}

// 取消编辑隐私协议
const onCancelEditPrivacy = () => {
  isEditingPrivacy.value = false
}

// 提交隐私协议更新
const onSubmitPrivacyUpdate = (data) => {
  console.log('隐私协议更新数据:', data)

  const loadingMessage = ElMessage({
    type: 'info',
    message: '正在更新隐私协议，请稍候...',
    duration: 0
  })

  setPrivacySetting(defaultApp.value.id, data.owner_setting, data.setting_list)
    .then((res) => {
      console.log('隐私协议更新结果:', res)
      loadingMessage.close()

      if (res.data && res.data.errcode === 0) {
        if (privacyVersion.value === 2) {
          ElMessage.success('开发版本隐私协议配置已更新成功！请记得重新提交审核以使配置生效。')
        } else {
          ElMessage.success('线上版本隐私协议配置已更新成功！')
        }

        // 关闭编辑模式和弹窗
        isEditingPrivacy.value = false
        privacyDialogVisible.value = false

        // 重新获取数据刷新显示
        setTimeout(() => {
          onGetPrivacySetting()
        }, 1000)
      } else {
        const errorMsg = res.data?.errmsg || '更新隐私协议失败'
        ElMessage.error(`更新隐私协议失败: ${errorMsg}`)
      }
    })
    .catch((err) => {
      console.error('更新隐私协议异常:', err)
      loadingMessage.close()
      ElMessage.error('更新隐私协议异常')
    })
}

const onSubmitAudit = () => {
  // 检查是否有审核中的版本
  if (auditVersion.value && auditVersion.value.status === 2) {
    ElMessage.warning('当前已有审核中的版本，请等待审核完成或撤回审核后再提交')
    return
  }

  // 打开提交审核弹窗
  auditForm.value.version_desc = ''
  auditDialogVisible.value = true
}

// 确认提交审核
const onConfirmSubmitAudit = () => {
  if (!auditForm.value.version_desc.trim()) {
    ElMessage.warning('请填写版本描述')
    return
  }

  auditLoading.value = true

  submitAudit(defaultApp.value.id, auditForm.value.version_desc)
    .then((res) => {
      console.log('提交审核结果:', res)
      if (res.data && res.data.errcode === 0) {
        ElMessage.success('提交审核成功！')
        auditDialogVisible.value = false
        // 刷新版本信息
        setTimeout(() => {
          loadVersionInfo()
        }, 1000)
      } else {
        const errorMsg = res.data?.errmsg || '提交审核失败'
        ElMessage.error(`提交审核失败: ${errorMsg}`)
      }
    })
    .catch((err) => {
      console.error('提交审核异常:', err)
    })
    .finally(() => {
      auditLoading.value = false
    })
}

// 撤回审核
const onUndoAudit = () => {
  if (!auditVersion.value || auditVersion.value.status !== 2) {
    ElMessage.warning('只有审核中的版本才能撤回')
    return
  }

  ElMessageBox.confirm(`确定要撤回审核吗？\n撤回后需要重新提交审核。`, '撤回审核确认', {
    confirmButtonText: '确定撤回',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      performUndoAudit()
    })
    .catch(() => {
      ElMessage.info('已取消撤回审核')
    })
}

// 执行撤回审核操作
const performUndoAudit = () => {
  const loadingMessage = ElMessage({
    type: 'info',
    message: '正在撤回审核，请稍候...',
    duration: 0
  })

  undoAudit(defaultApp.value.id)
    .then((res) => {
      console.log('撤回审核结果:', res)
      loadingMessage.close()

      if (res.data && res.data.errcode === 0) {
        ElMessage.success('审核撤回成功！')
        // 刷新版本信息
        setTimeout(() => {
          loadVersionInfo()
        }, 1000)
      } else {
        const errorMsg = res.data?.errmsg || '撤回审核失败'
        ElMessage.error(`撤回审核失败: ${errorMsg}`)
      }
    })
    .catch((err) => {
      console.error('撤回审核异常:', err)
      loadingMessage.close()
    })
}

const onGetAuditStatus = () => {
  getAuditStatus(defaultApp.value.id).then((res) => {
    console.log(res)
  })
}

// 处理版本信息数据
const processVersionInfo = (data) => {
  console.log('版本信息原始数据:', data)

  // 处理正式版本信息
  if (data.release_info) {
    currentVersion.value = {
      version: data.release_info.release_version || '未知版本',
      releaseTime: data.release_info.release_time ? new Date(data.release_info.release_time * 1000).toLocaleString('zh-CN') : '未知时间',
      remark: data.release_info.release_desc || '暂无描述',
      qrcode: ''
    }
  } else {
    currentVersion.value = null
  }

  // 处理体验版本信息
  if (data.exp_info) {
    latestVersion.value = {
      version: data.exp_info.exp_version || '未知版本',
      submitTime: data.exp_info.exp_time ? new Date(data.exp_info.exp_time * 1000).toLocaleString('zh-CN') : '未知时间',
      remark: data.exp_info.exp_desc || '暂无描述',
      qrcode: ''
    }
  } else {
    latestVersion.value = null
  }

  // 审核版本信息暂时保持为空，后续可以通过其他API获取
  auditVersion.value = null
}

// 处理审核状态数据
const processAuditStatus = (data) => {
  console.log('审核状态原始数据:', data)

  if (data.errcode === 0 && data.auditid) {
    const statusMap = {
      0: { text: '审核成功', type: 'success' },
      1: { text: '审核被拒绝', type: 'danger' },
      2: { text: '审核中', type: 'warning' },
      3: { text: '已撤回', type: 'info' },
      4: { text: '审核延后', type: 'warning' }
    }

    auditVersion.value = {
      version: data.user_version || '未知版本',
      submitTime: data.submit_audit_time ? new Date(data.submit_audit_time * 1000).toLocaleString('zh-CN') : '未知时间',
      remark: data.user_desc || '暂无描述',
      status: data.status,
      statusText: statusMap[data.status]?.text || '未知状态',
      statusType: statusMap[data.status]?.type || 'info',
      auditid: data.auditid,
      reason: data.reason || '',
      screenshot: data.screenshot || '',
      qrcode: ''
    }
  } else {
    auditVersion.value = null
  }
}

// 获取版本信息
const loadVersionInfo = () => {
  loading.value = true

  // 同时获取版本信息、审核状态和服务状态
  Promise.all([getVersionInfo(defaultApp.value.id), getLatestAuditStatus(defaultApp.value.id), getVisitStatus(defaultApp.value.id)])
    .then(([versionRes, auditRes, statusRes]) => {
      console.log('版本信息响应:', versionRes)
      console.log('审核状态响应:', auditRes)
      console.log('服务状态响应:', statusRes)

      // 处理版本信息
      if (versionRes.data && versionRes.data.errcode === 0) {
        processVersionInfo(versionRes.data)
      } else {
        console.error('获取版本信息失败:', versionRes.data?.errmsg || '未知错误')
      }

      // 处理审核状态
      if (auditRes.data && auditRes.data.errcode === 0) {
        processAuditStatus(auditRes.data)
      } else {
        console.log('暂无审核记录')
        auditVersion.value = null
      }

      // 处理服务状态
      if (statusRes.data && statusRes.data.errcode === 0) {
        serviceStatus.value = statusRes.data.status
      } else {
        console.error('获取服务状态失败:', statusRes.data?.errmsg || '未知错误')
        serviceStatus.value = null
      }
    })
    .catch((err) => {
      console.error('获取信息异常:', err)
    })
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  // 加载版本信息（包含审核状态）
  loadVersionInfo()

  getOpenTemplate(defaultApp.value.id).then((res) => {
    console.log(res)
  })
})
</script>

<style scoped>
.app-content {
  /* background-color: #fff; */
  border-radius: 4px;
  padding: 20px;
  box-shadow: var(--el-box-shadow-lighter);
  /* border: 1px solid var(--el-border-color); */
  /* margin: 40px 20px; */

  background-color: #fff;
  /* border-radius: 4px; */
  box-shadow: 0 1px 2px rgba(150, 150, 150, 0.3);
  padding: 30px 30px;
  margin-bottom: 20px;
}

:deep(.privacy-table .el-table__header-wrapper) {
  background-color: #f8f9fa;
}

:deep(.privacy-table .el-table__header th) {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 500;
}

:deep(.privacy-table .el-table__row:nth-child(even)) {
  background-color: #fafafa;
}
</style>
